import React, { Component } from 'react'
import store from '../../../redux'
import Api from '../../../config/api'
import axios from 'axios'
import Com from '../../../common/common'

import Navbar from '../../../Component/navbar'

import Table from 'antd/lib/table'
import Button from 'antd/lib/button'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import Input from 'antd/lib/input'
import Select from 'antd/lib/select'
import DatePicker from 'antd/lib/date-picker'
import Form from 'antd/lib/form'
import Popconfirm from 'antd/lib/popconfirm'

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;
const Option = Select.Option;
const FormItem = Form.Item;

let oper = null;

function formatDay(value) {
    if (parseInt(value, 10) < 10) {
        return '0' + value;
    }
    else {
        return value
    }
}

function getToday() {
    let now = new Date();
    let day, month, year;
    day = now.getDate();
    month = now.getMonth() + 1;
    year = now.getFullYear();
    return year + '-' + formatDay(month) + '-' + formatDay(day);
}

function getFullDay(year,month){
    let limit = 30;
    switch (month) {
        case '01':
        case '03':
        case '05':
        case '07':
        case '08':
        case '10':
        case '12':
          limit = 31;
          break;
        case '04':
        case '06':
        case '09':
        case '11':
          limit=30;
          break;
        case '02':
          limit = year% 4? 28 : 29;
          break;
        default:
          limit = 30;
      }
      return limit
}

function limitDate(data){
    const arr = data.split('-').map((item)=>{
        return parseInt(item,10)
    });
    const days = getFullDay(arr[0],arr[1]);
    if(arr[2]+6>days){
        if(arr[1] === 12){
            arr[0]+=1;
            arr[1]=1;
        }
        else{
            arr[1]+=1;
        }
        arr[2]=arr[2]+6-days;        
    }
    else{
        arr[2]+=7;
    }
    return arr.join('-')
}

function limitDate2(data){
    const arr = data.split('-').map((item)=>{
        return parseInt(item,10)
    });
    let days = 30;
    if(arr[1] === 1){
        days = getFullDay(arr[0]-1,12);
    }
    else{
        days = getFullDay(arr[0],arr[1]-1);
    }
    if(arr[2]-7<1){
        if(arr[1] === 1){
            arr[0]-=1;
            arr[1]=12;
        }
        else{
            arr[1]-=1;
        }
        arr[2]=arr[2]-6+days;        
    }
    else{
        arr[2]-=6;
    }
    return arr.join('-')
}

function limitDate3(data){
    const arr = data.split('-').map((item)=>{
        return parseInt(item,10)
    });
    const days = getFullDay(arr[0],arr[1]);
    if(arr[2]+1>days){
        if(arr[1] === 12){
            arr[0]+=1;
            arr[1]=1;
        }
        else{
            arr[1]+=1;
        }
        arr[2]=arr[2]+1-days;        
    }
    else{
        arr[2]+=1;
    }
    return arr.join('-')
}

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: getToday(),
            endDate: '',
            startMonent: null,
            endMoment: null,
            simSelectData: [{ index: '', desc: '全部' }],
            statusSelectData: [{ index: '', desc: '全部' }],
            SmsMsgNumEnum:[{ index: '', desc: '全部' }],
            allGateway:[{id:'',name:'全部'}]
        }
    }
    componentDidMount() {
        this.getSelect();
        this.setState({
            startMoment: moment(getToday(), "YYYY-MM-DD")
        })
    }
    async getSelect() {
        await Com.getSelection.call(this, 'SmsMsgOperatorEnum', 'simSelectData');
        await Com.getSelection.call(this, 'SmsMsgStatusEnum', 'statusSelectData');
        await Com.getSelection.call(this, 'SmsMsgNumEnum', 'SmsMsgNumEnum');
        axios.post(Api['queryAllGateway'],{}).then((res)=>{
            if (res) {
                const data = JSON.parse(JSON.stringify(res.data));
                data.unshift({id:'',name:'全部'});
                this.setState({
                    allGateway:data
                },()=>{
                    this.search();
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment || current > moment(limitDate3(getToday()),"YYYY-MM-DD") || current < moment(limitDate2(getToday()),"YYYY-MM-DD")
        }
        else {
            return current > moment(getToday(),"YYYY-MM-DD") || current < moment(limitDate2(getToday()),"YYYY-MM-DD")
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment || current > moment(limitDate(this.state.startDate), "YYYY-MM-DD") || current> moment(limitDate3(getToday()),"YYYY-MM-DD")
        }
        else {
            return current > moment(limitDate3(getToday()),"YYYY-MM-DD") || current < moment(limitDate2(getToday()),"YYYY-MM-DD")
        }
    }
    openCan1(){
        setTimeout(()=>{
        const ele = document.getElementsByClassName('ant-calendar-input')[0];
        ele.setAttribute('readOnly','readOnly');
        },200)
    }
    openCan2(){
        setTimeout(()=>{
        const ele = document.getElementsByClassName('ant-calendar-input')[0];
        ele.setAttribute('readOnly','readOnly');
        },200)
    }
    search() {
        let obj = {
            batchId: this.batchInput.input.value,
            messageId: this.messageInput.input.value,
            account: this.accountInput.input.value,
            phone: this.phoneInput.input.value,
            operator: this.simInput.rcSelect.state.value[0],
            gatewayId: this.channelInput.rcSelect.state.value[0],
            province:this.provinceInput.input.value,
            content:this.contentInput.input.value,
            accessNumber: this.inputInput.input.value,
            status: this.statusInput.rcSelect.state.value[0],
            result:this.resultInput.input.value,
            num: this.msgInput.rcSelect.state.value[0],
            // send: this.typeInput.rcSelect.state.value[0],
            startTime: this.state.startDate,
            endTime: this.state.endDate
        }
        this.props.search(obj, this.state.simSelectData, this.state.statusSelectData,this.state.allGateway)
    }
    render() {
        return (
            <Navbar ref={(item) => {oper=item}} className="account-operbar">
                <Form layout="inline">
                    <FormItem label="批次编号"><Input style={{ width: '140px' }} ref={(input) => { this.batchInput = input }} /></FormItem>
                    <FormItem label="消息编号"><Input style={{ width: '140px' }} ref={(input) => { this.messageInput = input }} /></FormItem>
                    <FormItem label="账号"><Input style={{ width: '130px' }} ref={(input) => { this.accountInput = input }} /></FormItem>
                    <FormItem label="手机号码"><Input style={{ width: '120px' }} ref={(input) => { this.phoneInput = input }} /></FormItem>
                    <FormItem label="运营商">
                        <Select ref={(input) => { this.simInput = input }} defaultValue="">
                            {this.state.simSelectData.map((item, index) => { return <Option key={index} value={item.index}>{item.desc}</Option> })}
                        </Select>
                    </FormItem>
                    <FormItem label="归属地"><Input style={{ width: '100px' }} ref={(input) => { this.provinceInput = input }} /></FormItem>
                    <FormItem label="短信内容"><Input style={{ width: '150px' }} ref={(input) => { this.contentInput = input }} /></FormItem>
                    {/*<FormItem label="城市"><Input style={{ width: '100px' }} ref={(input) => { this.cityInput = input }} /></FormItem>                    */}
                    <FormItem label="通道">
                        <Select ref={(input) => { this.channelInput = input }} style={{ width: '150px' }} defaultValue="">                    
                            {this.state.allGateway.map((item, index) => { return <Option key={index} value={item.id}>{item.name}</Option> })}                    
                        </Select>
                    </FormItem>
                    <FormItem label="接入号"><Input style={{ width: '100px' }} ref={(input) => { this.inputInput = input }} /></FormItem>
                    <FormItem label="状态">
                        <Select ref={(input) => { this.statusInput = input }} style={{ width: '100px' }} defaultValue="">
                            {this.state.statusSelectData.map((item, index) => { return <Option key={index} value={item.index}>{item.desc}</Option> })}
                        </Select>
                    </FormItem>
                    <FormItem label="状态描述"><Input style={{ width: '100px' }} ref={(input) => { this.resultInput = input }} /></FormItem>
                    <FormItem label="长短信">
                        <Select ref={(input) => { this.msgInput = input }} style={{ width: '100px' }} defaultValue="">
                            {this.state.SmsMsgNumEnum.map((item, index) => { return <Option key={index} value={item.index}>{item.desc}</Option> })}
                        </Select>
                    </FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" onOpenChange={this.openCan1} dropdownClassName="can1" allowClear={false} defaultValue={moment(this.state.startDate, "YYYY-MM-DD")} disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" onOpenChange={this.openCan2} dropdownClassName="can2" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    {/* <FormItem>
                        <Select ref={(input) => { this.typeInput = input }} style={{ width: '100px' }} defaultValue="true">
                            <Option value='true'>发送时间</Option>
                            <Option value='false'>接收时间</Option>
                        </Select>
                    </FormItem> */}
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                    </FormItem>
                </Form>
            </Navbar >
        )
    }
}

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 0,
            tableHeight: 300,
            tableData: this.props.tableData,
            currentPage: 1
        }
    }
    componentDidMount() {
        setTimeout(() => {
            let operbarHeight = oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
    }
    componentWillReceiveProps(nextprops) {
        this.setState({
            tableData: nextprops.tableData,
            dataNum: nextprops.dataNum,
            currntPage: nextprops.currentPage
        })
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight = oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    render() {
        const columns = [
            { title: '账号', dataIndex: 'account', key: '1', width: 220 },
            { title: '手机号码', dataIndex: 'phone', key: '2', width: 120 },
            { title: '运营商', dataIndex: 'operatorToName', key: '3', width: 100 },
            { title: '归属地', dataIndex: 'province', key: '4', width: 100 },
            // { title: '城市', dataIndex: 'city', key: '16', width: 100 },
            {
                title: '短信内容', key: '15', width: 340, render: (record) => {
                    return (
                        <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={record.content}>
                            <a>{record.contentAbb}</a>
                        </Popconfirm>
                    )
                }
            },
            { title: '短信条数', dataIndex: 'num', key: '5', width: 100 },
            { title: '通道', dataIndex: 'gatewayIdToName', key: '6', width: 220 },
            { title: '接入号', dataIndex: 'accessNumber', key: '7', width: 150 },
            {
                title: '发送状态', key: '8', width: 100, render: (record) => {
                    let color = '';
                    switch (record.status) {
                        case 1: color = '#FFC123'; break;
                        case 2: color = 'blue'; break;
                        case 3: color = 'green'; break;
                        case 4: color = '#EE1289'; break;
                        case 5: color = 'red'; break;
                        default: color = '#333';
                    }
                    return <span style={{ color }}>{record.statusToName}</span>
                }
            },
            {
                title: '状态描述', key: '9', width: 185, render: (record) => {
                    return (
                        <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={record.result}>
                            <a>{record.resultAbb}</a>
                        </Popconfirm>
                    )
                }
            },
            { title: '发送时间', dataIndex: 'sendTime', key: '10', width: 200 },
            { title: '接收时间', dataIndex: 'receiveTime', key: '11', width: 200 },
            { title: '耗时', dataIndex: 'countTime1', key: '12', width: 80 },
            { title: '批次编号', dataIndex: 'batchId', key: '13', width: 200 },
            { title: '消息编号', dataIndex: 'messageId', key: '14', width: 200 }
        ];
        return (
            <div className="account-table" style={{ marginTop: '10px' }}>
                <Table title={(data) => { return '短信发送列表' }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ x: 2615, y: this.state.tableHeight }}></Table>
            </div >
        )
    }
}


class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            totalNum: 0,
            tableData: [],
            searchParams: {},
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            simSelectData: [],
            statusSelectData: [],
            allGateway:[],
            loading: true,
            currentPage: 1,
        }
    }
    setParams(obj, simSelectData, statusSelectData,allGateway) {
        let data = JSON.parse(JSON.stringify(obj));
        this.setState({
            searchParams: data,
            simSelectData,
            statusSelectData,
            allGateway
        }, () => {
            this.search('btn');
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        // data.send = data.send === 'true' ? true : false;
        axios.post(Api['queryMsgByParams'], data).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach((item, index) => {
                    item.key = index;
                    this.state.simSelectData.forEach((item1) => { if (parseInt(item.operator, 10) === parseInt(item1.index, 10)) { item.operatorToName = item1.desc } })
                    this.state.statusSelectData.forEach((item1) => { if (parseInt(item.status, 10) === parseInt(item1.index, 10)) { item.statusToName = item1.desc } })
                    this.state.allGateway.forEach((item1) => { if (parseInt(item.gatewayId, 10) === parseInt(item1.id, 10)) { item.gatewayIdToName = item1.name } })                    
                    if (item.countTime || item.countTime === 0) {
                        item.countTime1 = item.countTime + 's';
                    }
                    if (item.content) {
                        item.contentAbb = Com.abbrData(item.content, 20);
                    }
                    if (item.result) {
                        item.resultAbb = Com.abbrData(item.result, 9);
                    }
                })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag') })
    }
    render() {
        return <div>
            <OperBar paginationData={this.state.paginationData} search={this.setParams.bind(this)}></OperBar>
            <Spin spinning={this.state.loading} indicator={antIcon}>
                <Table1 currentPage={this.state.currentPage} tableData={this.state.tableData} dataNum={this.state.totalNum} changePageSize={this.changePageSize.bind(this)} changePage={this.changePage.bind(this)}></Table1>
            </Spin>
        </div>
    }
}

export default Box